#!/bin/bash

if [ $# -lt 2 ]; then
   echo "You must specify both the old path and the new"
   exit 1
else
   oldPath="$1"
   newPath="$2"
   echo "Moving repo submodule $1 to $2 [enter to continue]"
   read ok
fi


orginUrl=`git config --local --get submodule.${oldPath}.url`

# Do some sanity checks

if git submodule status ${oldPath} 2>&1| grep pathspec || [ "${orginUrl}" == "" ]; then
    echo "Doesn't look like ${oldPath} is an existing submodule";
    exit 1
fi

if [ -e "${newPath}" ]; then
    echo "Something already exists at ${newPath}...can't repo move there"
    rm -rf ${newPath}
    #exit 1
fi

## add new submodule
mkdir -p `dirname "${newPath}"`
git submodule add --force "${orginUrl}" "${newPath}"

## remove old submodule
git config -f .git/config --remove-section "submodule.${oldPath}"
git config -f .gitmodules --remove-section "submodule.${oldPath}"
git rm --cached "${oldPath}"
rm -rf "${oldPath}"              ## remove old src
rm -rf ".git/modules/${oldPath}" ## cleanup gitdir (housekeeping)

## commit
git add .gitmodules
git commit -m "Renamed ${oldPath} to ${newPath}"
